package com.mantou.scucorse.core.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mantou.scucorse.core.entity.ScuCourse;
import com.mantou.scucorse.core.repository.ScuCourseRepository;
import com.mantou.scucorse.core.service.ScuCourseService;
import com.mantou.scucorse.utils.CourseStatus;
import com.mantou.scucorse.utils.SystemInfo;

@Service
public class ScuCourseService {


	@Resource
	private ScuCourseRepository scuCourseRepo;

	@Transactional
	public int create(ScuCourse scuCourse) {
		 scuCourseRepo.insert(scuCourse);
		 return scuCourse.getId();
	}

	@Transactional
	public int createSelective(ScuCourse scuCourse) {
		 scuCourseRepo.insertSelective(scuCourse);
		 return scuCourse.getId();
	}

	@Transactional
	public int deleteByPrimaryKey(Integer id) {
		return scuCourseRepo.deleteByPrimaryKey(id);
	}

	@Transactional(readOnly = true)
	public ScuCourse findByPrimaryKey(Integer id) {
		ScuCourse scuCourse = scuCourseRepo.selectByPrimaryKey(id);
		return scuCourse;
	}

	@Transactional(readOnly = true)
	public int selectCount(ScuCourse scuCourse) {
		return scuCourseRepo.selectCount(scuCourse);
	}

	@Transactional
	public int updateByPrimaryKey(ScuCourse scuCourse) {
		return scuCourseRepo.updateByPrimaryKey(scuCourse);
	}
	
	@Transactional
	public int updateByPrimaryKeySelective(ScuCourse scuCourse) {
		return scuCourseRepo.updateByPrimaryKeySelective(scuCourse);
	}

	public List<ScuCourse> findAvailable() {
		// TODO Auto-generated method stub
		List<ScuCourse> rets ;
		ScuCourse queryCourse = new ScuCourse();
		queryCourse.setStatus(CourseStatus.INITED.getStatus());
		rets = scuCourseRepo.selectPage(queryCourse,
				new PageRequest(0,SystemInfo.batchNumber,new Sort(new Order(Direction.ASC,"lasdupdate"))));
		int retsize = rets.size();
		if(retsize >= SystemInfo.batchNumber){
			return rets;
		}
		queryCourse.setStatus(CourseStatus.RUNNING.getStatus());
		rets.addAll(scuCourseRepo.selectPage(queryCourse,
				new PageRequest(0,SystemInfo.batchNumber - retsize,new Sort(new Order(Direction.ASC,"lasdupdate")))));
		return rets;
	}

	public ScuCourse find(ScuCourse queryScuCourse) {
		// TODO Auto-generated method stub
		List<ScuCourse> rets = scuCourseRepo.selectPage(queryScuCourse, new PageRequest(0,1));
		if(rets.size() != 0){
			return rets.get(0);
		}
		return null;
	}

}
